<template>
  <div>
    <Card class="userCard">
      <div style="font-size:16px">用户列表</div>
      <Divider></Divider>
      <!-- 查询行 -->
      <!-- <Row :gutter="50"> -->
      <Form :model="form">
        <Row gutter="30">
          <i-col span="5">
            <FormItem>
              <Input v-model="form.username" placeholder="用户姓名" clearable />
            </FormItem>
          </i-col>
          <i-col span="5">
            <FormItem>
              <Select v-model="form.active" placeholder="状态" clearable>
                <Option v-for="item in stateList" :key="item.key" :value="item.key">{{ item.value }}</Option>
              </Select>
            </FormItem>
          </i-col>
        </Row>
        <Row :gutter="50">
          <i-col span="8">
            <FormItem>
              <Button type="primary" @click="userQuery(0)" :loading="queryLoading" style="margin-right:20px;">查询</Button>
              <Button type="primary" @click="addUser">新建用户</Button>
            </FormItem>
          </i-col>
        </Row>
      </Form>
      <!-- </Row> -->
      <!-- 表格 -->
      <Table :columns="columns1" :data="data1">
        <template slot-scope="{ row }" slot="indexNo">
          {{
          row._index + 1
          }}
        </template>
        <template slot-scope="{ row }" slot="employeeNo">
          <span v-show="
              row.rankNo == '市公司内勤' ||
                row.rankNo == '省公司内勤' ||
                row.rankNo == '总公司内勤'
            ">-</span>
          <span v-show="
              row.rankNo != '市公司内勤' &&
                row.rankNo != '省公司内勤' &&
                row.rankNo != '总公司内勤'
            ">{{ row.employeeNo }}</span>
        </template>
        <template slot-scope="{ row }" slot="isDuty">
          <span v-show="row.isDuty == 0">
            <Button type="primary" class="onTheJob">在职</Button>
          </span>
          <span v-show="row.isDuty == 1">
            <Button disabled class="onTheJob">离职</Button>
          </span>
          <span v-show="row.isDuty == '-'">-</span>
        </template>
        <template slot-scope="{ row }" slot="isInnerLine">
          <i-switch v-model="row.isInnerLine" true-value='Y' false-value='N' @on-change="changeIsInnerLine(row)">
            <span slot="open">是</span>
            <span slot="close">否</span>
          </i-switch>
        </template>
        <template slot-scope="{ row }" slot="operate">
          <Button :disabled="row.isDuty == 1" type="primary" @click="resetPswShow(row)">修改信息</Button>
          <i-switch :before-change="handleBeforeChange" v-model="row.active" @on-change="switchChange(...arguments, row)" style="margin-left:20px" :disabled="row.isDuty == 1" :loading="switchLoading"></i-switch>
          <span :class="row.active ? 'blue' : 'gray'">
            <span v-show="row.active">活跃</span>
            <span v-show="!row.active">不活跃</span>
          </span>
        </template>
      </Table>
      <!-- 新建用户弹窗 -->
      <Modal footer-hide="true" :value="addUserModal" :mask-closable="false" @on-visible-change="modalVisibleChange" width="571" class-name="addClass">
        <span slot="header" style="color:#fff;font-size:16px">新建用户</span>
        <div style="width:80%;margin:0 auto">
          <Form ref="addUserForm" :model="addUserForm" :rules="addUserRules">
            <Row gutter="40">
              <i-col span="12">
                <FormItem prop="account">
                  <Input v-model="addUserForm.account" placeholder="账号" />
                </FormItem>
              </i-col>
              <i-col span="12">
                <FormItem prop="name">
                  <Input v-model="addUserForm.name" placeholder="姓名" />
                </FormItem>
              </i-col>
            </Row>
            <Row gutter="40">
              <i-col span="12">
                <FormItem prop="password">
                  <Input type="password" password v-model="addUserForm.password" placeholder="密码" />
                </FormItem>
              </i-col>
              <i-col span="12">
                <FormItem prop="rePassword">
                  <Input type="password" password v-model="addUserForm.rePassword" placeholder="再次输入密码" />
                </FormItem>
              </i-col>
            </Row>
            <Row gutter="40">
              <i-col span="12">
                <FormItem prop="company">
                  <Input v-model="addUserForm.company" placeholder="公司" />
                </FormItem>
              </i-col>
              <i-col span="12">
                <FormItem prop="phone">
                  <Input v-model="addUserForm.phone" placeholder="电话" />
                </FormItem>
              </i-col>
            </Row>
            <Row gutter="40">
              <i-col span="12">
                <FormItem prop="email">
                  <Input v-model="addUserForm.email" placeholder="邮箱" />
                </FormItem>
              </i-col>
              <i-col span="12">
                <FormItem prop="workYear">
                  <Input v-model="addUserForm.workYear" placeholder="工作年限" />
                </FormItem>
              </i-col>
            </Row>
            <Row gutter="40">
              <i-col span="12">
                <FormItem prop="level">
                  <Select v-model="addUserForm.level" placeholder="职级" @on-change="levelChange()" clearable>
                    <Option v-for="item in levelList" :key="item.key" :value="item.key">{{ item.value }}</Option>
                  </Select>
                </FormItem>
              </i-col>
              <i-col span="12">
                <FormItem prop="employeeNo" v-if="!empNoFlag">
                  <Input v-model="addUserForm.employeeNo" placeholder="员工工号" />
                </FormItem>
                <FormItem prop="employeeNo" v-else>
                  <Input v-model="addUserForm.employeeNo" placeholder="员工工号" :disabled="empNoFlag" />
                </FormItem>
              </i-col>
            </Row>
            <Row gutter="40">
              <i-col span="12">
                <FormItem prop="organization">
                  <Cascader change-on-select :data="organizationList" @on-change="changeOrganization" v-model="addUserForm.organization" placeholder="管理机构" change-on-select clearable></Cascader>
                </FormItem>
              </i-col>
              <i-col span="12">
                <FormItem prop="sex">
                  <RadioGroup v-model="addUserForm.sex">
                    <Radio label="0">男</Radio>
                    <Radio label="1">女</Radio>
                  </RadioGroup>
                </FormItem>
              </i-col>
            </Row>
            <Row gutter="40">
              <i-col span="12">
                <FormItem prop="isInnerLine" label="是否内线拨号：">
                  <i-switch v-model="addUserForm.isInnerLine" true-value='Y' false-value='N'>
                    <span slot="open">是</span>
                    <span slot="close">否</span>
                  </i-switch>
                </FormItem>
              </i-col>
            </Row>
            <Row gutter="40">
              <i-col span="12" style="text-align:right">
                <Button type="primary" @click="addSubmit" :loading="addSubmitLoading">保存</Button>
              </i-col>
              <i-col span="12">
                <Button type="primary" @click="addCancel">取消</Button>
              </i-col>
            </Row>
          </Form>
        </div>
      </Modal>
      <!-- 修改信息弹窗 -->
      <Modal footer-hide="true" :value="resetPswModal" :mask-closable="false" @on-visible-change="modalVisibleChange2" width="640" class-name="updateClass">
        <span slot="header" style="color:#fff;font-size:16px">信息修改</span>
        <div style="width:90%; margin:0 auto;">
          <Form ref="resetPswForm" :model="resetPswForm" :rules="resetPswRules">
            <Row>
              <i-col span="3" style="height:32px;line-height:32px; text-align:right; padding-right:5px;">
                <span>重置密码</span>
              </i-col>
              <i-col span="8" style="margin-right:20px;">
                <FormItem prop="password">
                  <Input type="password" v-model="resetPswForm.password" placeholder="重置的密码" password />
                </FormItem>
              </i-col>
              <i-col span="4" style="height:32px;line-height:32px; text-align:right; padding-right:5px;">
                <span>确认重置密码</span>
              </i-col>
              <i-col span="8">
                <FormItem prop="rePassword">
                  <Input type="password" v-model="resetPswForm.rePassword" placeholder="确认重置的密码" password />
                </FormItem>
              </i-col>
            </Row>
            <Row>
              <i-col span="3" style="height:32px;line-height:32px; text-align:right; padding-right:5px;">
                <span>公司</span>
              </i-col>
              <i-col span="8" style="margin-right:20px;">
                <FormItem prop="oldCompany">
                  <Input type="text" v-model="resetPswForm.oldCompany" placeholder="原公司名称" clearable />
                </FormItem>
              </i-col>
              <i-col span="4" style="height:32px;line-height:32px; text-align:right; padding-right:5px;">
                <span>工作年限</span>
              </i-col>
              <i-col span="8">
                <FormItem prop="workYear">
                  <Input type="text" v-model="resetPswForm.workYear" placeholder="工作年限" clearable />
                </FormItem>
              </i-col>
            </Row>
            <Row>
              <i-col span="3" style="height:32px;line-height:32px; text-align:right; padding-right:5px;">
                <span>职级</span>
              </i-col>
              <i-col span="8" style="margin-right:20px;">
                <FormItem prop="workLevel">
                  <Select v-model="resetPswForm.workLevel" placeholder="职级" @on-change="levelChange2()" clearable>
                    <Option v-for="item in levelList" :key="item.key" :value="item.key">{{ item.value }}</Option>
                  </Select>
                </FormItem>
              </i-col>
              <i-col span="4" style="height:32px;line-height:32px; text-align:right; padding-right:5px;">
                <span>管理机构</span>
              </i-col>
              <i-col span="8">
                <FormItem prop="organization">
                  <Cascader change-on-select :data="organizationList" v-model="resetPswForm.organization" placeholder="管理机构" clearable></Cascader>
                </FormItem>
              </i-col>
            </Row>
            <Row>
              <i-col span="3" style="height:32px;line-height:32px; text-align:right; padding-right:5px;">
                <span>性别</span>
              </i-col>
              <i-col span="8">
                <FormItem prop="sex">
                  <RadioGroup v-model="resetPswForm.sex">
                    <Radio label="0">男</Radio>
                    <Radio label="1">女</Radio>
                  </RadioGroup>
                </FormItem>
              </i-col>
            </Row>
            <Row>
              <FormItem class="btngroup">
                <i-col span="8" style="text-align:right">
                  <Button type="primary" @click="resetPswSubmit" :loading="repasswordSubmit">确定</Button>
                </i-col>
                <i-col span="8" style="text-align:left; padding-left:20px;">
                  <Button type="primary" @click="resetPswCancel">取消</Button>
                </i-col>
              </FormItem>
            </Row>
          </Form>
        </div>
      </Modal>
      <!-- 当前员工录入的管理机构与核心系统对应管理机构不同（核心为****），确认保存？ ----判断的是新建用户的-->
      <Modal v-model="stopModal" :mask-closable="false" header-hide="true" footer-hide="true" width="450" class-name="stopClass" @on-visible-change="stopModalChange">
        <div>
          <span style="font-size:28px; color:#FF9900;margin: 0 10px;">
            <Icon type="ios-help-circle" />
          </span>
          <span slot="header" style="font-size:16px">保存确认</span>
        </div>
        <span style="display:block;margin:20px 0 20px 60px; font-size:14px;">
          当前员工录入的管理机构与核心系统对应管理机构不同（核心为{{
          stopManagecom
          }}），确认保存？
        </span>
        <div style="width:400px; text-align:right;">
          <Button type="primary" @click="stopSubmit" :loading="stoploading" style="margin-right:20px;">确定</Button>
          <Button @click="stopCancel">取消</Button>
        </div>
      </Modal>
      <!-- 当前员工录入的管理机构与核心系统对应管理机构不同（核心为****），确认保存？ ----判断的是修改用户的-->
      <Modal v-model="stopModal2" :mask-closable="false" header-hide="true" footer-hide="true" width="450" class-name="stopClass" @on-visible-change="stopModalChange2">
        <div>
          <span style="font-size:28px; color:#FF9900;margin: 0 10px;">
            <Icon type="ios-help-circle" />
          </span>
          <span slot="header" style="font-size:16px">保存确认</span>
        </div>
        <span style="display:block;margin:20px 0 20px 60px; font-size:14px;">
          当前员工录入的管理机构与核心系统对应管理机构不同（核心为{{
          stopManagecom2
          }}），确认保存？
        </span>
        <div style="width:400px; text-align:right;">
          <Button type="primary" @click="stopSubmit2" :loading="stoploading2" style="margin-right:20px;">确定</Button>
          <Button @click="stopCancel2">取消</Button>
        </div>
      </Modal>
      <!-- 是否活跃弹窗 -->
      <!-- <Modal v-model="delModal" header-hide="true" footer-hide="true" width="450">
        <div>
          <span style="font-size:28px; color:#FF9900;margin: 0 10px;"><Icon type="ios-help-circle" /></span>
          <span slot="header" style="font-size:16px">切换确认</span>
        </div>
        <span style="display:block;margin:20px 0 20px 60px; font-size:14px;">您确定切换活跃状态吗？</span>
        <div style="width:400px; text-align:right;">
          <Button type="primary" @click="delSubmit" :loading="roleSubmit" style="margin-right:20px;">确定</Button>
          <Button @click="delCancel">取消</Button>
        </div>
      </Modal>-->
      <!-- 分页 -->
      <Row>
        <i-col span="24" style="text-align:right;margin-top:20px">
          <Page :total="total" show-total show-sizer @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeOptions" :current="pageIndex" :page-size="pageSize" />
        </i-col>
      </Row>
      <Button type="primary" @click="info" v-if="false"></Button>
    </Card>
  </div>
</template>
<script>
import Cookies from 'js-cookie'
export default {
  data() {
    // 字母数字校验
    const validatorAccount = (rule, value, callback) => {
      let accountReg = /^[0-9A-Za-z]+$/
      if (value != '' && !accountReg.test(value)) {
        callback(new Error('只支持数字字母录入'))
      } else {
        callback()
      }
    }
    //长度至少8位且包含数字字母
    const validatorLength = (rule, value, callback) => {
      let accountReg = /^(?=.*[A-Za-z])(?=.*[0-9])(?=.*[~!@#$%^&*()_+|<>,.?/\\:;'\[\]{}\"\-]).{8,}$/
      if (value != '' && value.match(accountReg)== null) {
        callback(new Error('长度至少8位含字母,数字,特殊字符'))
      } else {
        callback()
      }
    }

    // 两次密码相同校验
    const validatorPsw = (rule, value, callback) => {
      if (this.addUserForm.rePassword !== '') {
        this.$refs.addUserForm.validateField('rePassword')
        callback()
      } else if (this.resetPswForm.rePassword !== '') {
        this.$refs.resetPswForm.validateField('rePassword')
        callback()
      } else if (
        this.resetPswForm.password !== '' &&
        value !== this.resetPswForm.password
      ) {
        callback('再次确认密码不能为空')
      } else {
        callback()
      }
      callback()
    }
    // 两次密码相同校验
    const validatorResetPsw = (rule, value, callback) => {
      if (this.addUserModal) {
        if (!this.addUserForm.password || value !== this.addUserForm.password) {
          callback('两次输入密码不匹配')
        } else {
          callback()
        }
      }
      if (this.resetPswModal) {
        if (
          !this.resetPswForm.password ||
          value !== this.resetPswForm.password
        ) {
          callback('两次输入密码不匹配')
        } else {
          callback()
        }
      }
    }
    // 管理机构空校验
    const validatorOrganization = (rule, value, callback) => {
      if (value == '' || value == null) {
        callback(new Error('管理机构不能为空'))
      }
      callback()
    }
    // 员工工号校验
    const validatorEmployeeNo = (rule, value, callback) => {
      let accountReg = /^[0-9A-Za-z]+$/
      console.log(value)
      if (
        this.addUserForm.level != 'S30' &&
        this.addUserForm.level != 'S31' &&
        this.addUserForm.level != 'S32'
      ) {
        if (value != '') {
          if (!accountReg.test(value)) {
            callback(new Error('只支持数字字母录入'))
          } else {
            callback()
          }
        } else {
          callback('员工工号不能为空')
        }
      }
      callback()
    }
    // 手机号码校验
    const validatorPhone = (rule, value, callback) => {
      let accountReg1 = /^[0-9]+$/
      if (!accountReg1.test(value)) {
        callback(new Error('手机号码只能输入数字'))
      }
      if (value.length !== 11) {
        callback(new Error('手机号码位数需为11位'))
      }
      let accountReg = /^[1][3-9][0-9]+$/
      if (value != '' && !accountReg.test(value)) {
        callback(new Error('移动电话必需以13-19开头'))
      }
      callback()
    }
    // 邮箱校验
    const validatorEmail = (rule, value, callback) => {
      var emailReg3 = /^[\w\.\-\@]+$/
      if (!emailReg3.test(value)) {
        callback(new Error('邮箱只能包含字符数字和.-_@'))
      }
      var emailReg = /^([\w\-\.\u4e00-\u9fa5])+\@([\w\-\.])+\.([A-Za-z]{2,8})$/
      if (!emailReg.test(value)) {
        callback(new Error('请输入有效的邮箱地址'))
      }
      var emailReg2 = /^([\w\-\.\u4e00-\u9fa5\@\.])*(\@\.|\.\@)+([\w\-\.\u4e00-\u9fa5])*$/
      if (emailReg2.test(value)) {
        callback(new Error('请输入有效的邮箱地址'))
      }
      callback()
    }

    // 年限
    const workYearValidtor = (rule, value, callback) => {
      // console.log(value)
      if (value) {
        callback()
      } else {
        callback('工作年限不能为空')
      }
    }

    return {
      // 当前页码
      pageIndex: 1,
      // 每页记录数量
      pageSize: 10,
      //  每页条数切换的配置
      pageSizeOptions: [5, 10, 15, 20],
      //  总数量
      total: 0,
      pageObj: null,
      form: {
        username: '',
        active: ''
      },
      stateList: [
        { key: '0', value: '活跃' },
        { key: '1', value: '不活跃' },
        { key: '2', value: '全部' }
      ],
      // 增加用户表单
      addUserForm: {
        account: '',
        name: '',
        password: '',
        company: '',
        rePassword: '',
        phone: '',
        employeeNo: '',
        organization: '',
        email: '',
        workYear: '',
        level: '',
        sex: '',
        isInnerLine:'N'
      },
      addUserRules: {
        account: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          { required: true, message: '账号不能为空', trigger: 'change' },
          { validator: validatorAccount, trigger: 'blur' },
          { validator: validatorAccount, trigger: 'change' }
        ],
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { required: true, message: '姓名不能为空', trigger: 'change' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { required: true, message: '密码不能为空', trigger: 'change' },
          // { validator: validatorAccount, trigger: 'blur' },
          // { validator: validatorAccount, trigger: 'change' },
          { validator: validatorLength, trigger: 'blur' },
          { validator: validatorLength, trigger: 'change' },
          { validator: validatorPsw, trigger: 'blur' },
          { validator: validatorPsw, trigger: 'change' }
        ],
        rePassword: [
          { required: true, message: '再次输入密码不能为空', trigger: 'blur' },
          {
            required: true,
            message: '再次输入密码不能为空',
            trigger: 'change'
          },
          // { validator: validatorAccount, trigger: 'blur' },
          // { validator: validatorAccount, trigger: 'change' },
          { validator: validatorResetPsw, trigger: 'blur' },
          { validator: validatorResetPsw, trigger: 'change' }
        ],
        company: [
          { required: true, message: '公司不能为空', trigger: 'blur' },
          { required: true, message: '公司不能为空', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '电话不能为空', trigger: 'blur' },
          { required: true, message: '电话不能为空', trigger: 'change' },
          { validator: validatorPhone, trigger: 'blur' },
          { validator: validatorPhone, trigger: 'change' }
        ],
        employeeNo: [
          { validator: validatorEmployeeNo, trigger: 'blur' },
          { validator: validatorEmployeeNo, trigger: 'change' }
        ],
        organization: [
          { validator: validatorOrganization, trigger: 'blur' },
          { validator: validatorOrganization, trigger: 'change' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { required: true, message: '邮箱不能为空', trigger: 'change' },
          { validator: validatorEmail, trigger: 'blur' }
        ],
        workYear: [
          { required: true, message: '工作年限不能为空', trigger: 'blur' },
          { required: true, message: '工作年限不能为空', trigger: 'change' }
        ],
        level: [
          { required: true, message: '职级不能为空', trigger: 'blur' },
          { required: true, message: '职级不能为空', trigger: 'change' }
        ],
        sex: [
          { required: true, message: '性别不能为空', trigger: 'blur' },
          { required: true, message: '性别不能为空', trigger: 'change' }
        ]
      },
      // 重置密码表单
      resetPswForm: {
        password: '',
        rePassword: '',
        oldCompany: '',
        workYear: '',
        workLevel: '',
        organization: {},
        sex: ''
      },
      resetPswRules: {
        password: [
          // { validator: validatorAccount, trigger: 'blur' },
          // { validator: validatorAccount, trigger: 'change' },
          { validator: validatorLength, trigger: 'blur' },
          { validator: validatorLength, trigger: 'change' },
          { validator: validatorPsw, trigger: 'blur' },
          { validator: validatorPsw, trigger: 'change' }
        ],
        rePassword: [
          // { validator: validatorAccount, trigger: 'blur' },
          // { validator: validatorAccount, trigger: 'change' },
          { validator: validatorResetPsw, trigger: 'blur' },
          { validator: validatorResetPsw, trigger: 'change' }
        ],
        oldCompany: [
          { required: true, message: '公司不能为空', trigger: 'blur' },
          { required: true, message: '公司不能为空', trigger: 'change' }
        ],
        workYear: [
          { validator: workYearValidtor, trigger: 'blur' },
          { validator: workYearValidtor, trigger: 'change' }
        ],
        workLevel: [
          { required: true, message: '职级不能为空', trigger: 'blur' },
          { required: true, message: '职级不能为空', trigger: 'change' }
        ],
        organization: [
          { validator: validatorOrganization, trigger: 'blur' },
          { validator: validatorOrganization, trigger: 'change' }
        ],
        sex: [
          { required: true, message: '性别不能为空', trigger: 'blur' },
          { required: true, message: '性别不能为空', trigger: 'change' }
        ]
      },
      // 表格数据
      columns1: [
        {
          title: '序号',
          key: 'indexNo',
          slot: 'indexNo',
          align: 'center',
          width: '80'
        },
        {
          title: '姓名',
          key: 'name',
          align: 'center',
          width: '110'
        },
        {
          title: '账号',
          key: 'username',
          align: 'center',
          width: '160'
        },
        {
          title: '员工工号',
          key: 'employeeNo',
          slot: 'employeeNo',
          align: 'center',
          width: '120'
        },
        {
          title: '公司',
          key: 'company',
          align: 'center',
          width: '120'
        },
        {
          title: '管理机构',
          key: 'managecom',
          align: 'center',
          width: '100'
        },
        {
          title: '邮箱',
          key: 'email',
          align: 'center',
          width: '180'
        },
        {
          title: '电话',
          key: 'phone',
          align: 'center',
          width: '160'
        },
        {
          title: '职级',
          key: 'rankNo',
          align: 'center',
          width: '120'
        },
        {
          title: '工作年限',
          key: 'workAge',
          align: 'center',
          width: '120'
        },
        {
          title: '是否在职',
          key: 'isDuty',
          align: 'center',
          width: '120',
          slot: 'isDuty'
        },
        {
          title: '是否内线拨号',
          key: 'isInnerLine',
          align: 'center',
          width: '120',
          slot: 'isInnerLine'
        },
        {
          title: '操作',
          key: 'operate',
          slot: 'operate',
          minWidth: 280
        }
      ],
      data1: [],
      // 机构列表
      organizationList: [],
      // 职级列表
      levelList: {},
      // 开关状态
      activeStatus: true,
      addUserModal: false,
      resetPswModal: false,
      pageObj: '',
      currentRow: '',
      switchLoading: false,
      addSubmitLoading: false,
      repasswordSubmit: false,
      queryLoading: false,
      // 判断工号是否禁用---新增用户
      empNoFlag: false,
      stopModal: false,
      addObj: {},
      stoploading: false,
      stopManagecom: '',
      // 修改用户判断工号机构
      empNoFlag2: false,
      stopModal2: false,
      stoploading2: false,
      stopManagecom2: '',
      updateObj: {}
    }
  },
  methods: {
    info(tip) {
      this.$Message.warning(tip)
    },
    // 下拉内容若选择“市公司内勤”、“省公司内勤”、“总公司内勤”，无需录入【员工工号】，对应控件置灰不可录入
    levelChange() {
      if (
        this.addUserForm.level == 'S30' ||
        this.addUserForm.level == 'S31' ||
        this.addUserForm.level == 'S32'
      ) {
        this.addUserForm.employeeNo = null
        this.empNoFlag = true
      } else {
        this.addUserForm.employeeNo = ''
        this.empNoFlag = false
      }
      // console.log(this.addUserForm.level);
    },
    levelChange2() {
      if (
        this.resetPswForm.workLevel == 'S30' ||
        this.resetPswForm.workLevel == 'S31' ||
        this.resetPswForm.workLevel == 'S32'
      ) {
        this.currentRow.employeeNo = ''
        this.empNoFlag2 = true
      } else {
        this.empNoFlag2 = false
      }
      // console.log(this.addUserForm.level);
    },
    // 内线拨号切换
    changeIsInnerLine(row){
      $.ajax('../api/user/updateLine/' + row.employeeNo, {
        method: 'put',
        contentType: 'application/json;charset=utf-8',
        beforeSend: function(xhr) {
          xhr.setRequestHeader(
            'Authorization',
            sessionStorage.getItem('credentials')
          )
        },
        success: res => {
          if (res.data === true) {
            this.pageQuery()
          }
        },
        error: res => {
          this.$Message.info(res.msg)
        }
      })
    },
    // 开关转换
    switchChange(value, row) {
      let obj = {
        employeeNo: row.employeeNo
      }
      this.switchLoading = true
      $.ajax('../api/user/update/' + obj.employeeNo, {
        method: 'put',
        contentType: 'application/json;charset=utf-8',
        beforeSend: function(xhr) {
          xhr.setRequestHeader(
            'Authorization',
            sessionStorage.getItem('credentials')
          )
        },
        success: res => {
          if (res.data === true) {
            this.switchLoading = false
            this.$Message.info(res.msg)
          }
        },
        error: res => {
          this.switchLoading = false
          this.$Message.info(res.msg)
        }
      })
      if (value == true) {
        this.activeStatus = true
      }
      if (value == false) {
        this.activeStatus = false
      }
    },

    // 切换确认
    handleBeforeChange() {
      return new Promise(resolve => {
        this.$Modal.confirm({
          title: '切换确认',
          content: '您确认要切换活跃状态吗？',
          onOk: () => {
            resolve()
          }
        })
      })
    },

    // 分页设置
    pageChange(pageIndex) {
      this.pageIndex = pageIndex
      this.pageQuery()
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize
      this.pageQuery()
    },

    // 查询
    userQuery(tmp) {
      if (tmp != 1) {
        this.queryLoading = true
      }

      this.pageIndex = 1
      this.pageSize = 10

      let obj = {
        index: this.pageIndex,
        pageSize: this.pageSize,
        name: this.form.username,
        active: this.form.active
      }
      if (this.form.active == 2) {
        obj.active = null
      }
      for (let item in obj) {
        if (obj[item] == null || obj[item].length == 0 || obj[item] == '') {
          delete obj[item]
        }
      }
      this.pageObj = obj
      this.api.getOneUser(obj).then(res => {
        if (res.code == 200 && res.data ) {
          this.queryLoading = false
          this.data1 = res.data.records
          this.data1.forEach(element => {
            if (element.active) {
              element.active = element.active == 0 ? true : false
            }
          })
          this.total = res.data.total
          if (tmp != 1) {
            this.$Message.info(res.msg)
          }
        } else {
          this.data1 = []
          this.total = 0
          this.queryLoading = false
          this.$Message.info(res.msg)
        }
      })
    },

    // 分页查询
    pageQuery() {
      this.pageObj.index = this.pageIndex
      this.pageObj.pageSize = this.pageSize
      this.api.getOneUser(this.pageObj).then(res => {
        if (res.code == 200 && res.data.total > 0) {
          this.data1 = res.data.records
          this.data1.forEach(element => {
            if (element.active) {
              element.active = element.active == 0 ? true : false
            }
          })
          this.total = res.data.total
        } else {
          this.data1 = []
          this.total = 0
          this.$Message.info(res.msg)
        }
      })
    },

    // 进入页面初始化
    initialize() {
      this.userQuery(1)
      // this.api.selectUerList().then(res => {
      //   if (res.code == 200 && res.data != null) {
      //     this.organizationList = res.data[0].listKeyValueVOS
      //   } else {
      //     this.organizationList = []
      //   }
      // })
      this.api.remanagecomList().then(res => {
        if (res.code == 200 && res.data != null) {
          let arr = []
          arr.push(res.data)
          arr.forEach(one=>{
            one.value = one.comcode
            one.label = one.comcode + '-' + one.name
            one.children = one.chilDren || []
            if (one.children) {
              one.chilDren.forEach(two=>{
                two.value = two.comcode
                two.label = two.comcode + '-' + two.name
                two.children = two.chilDren || []
                if (two.children) {
                  two.children.forEach(three=>{
                    three.value = three.comcode
                    three.label = three.comcode + '-' + three.name
                    three.children = three.chilDren || []
                    if (three.children) {
                      three.children.forEach(four=>{
                        four.value = four.comcode
                        four.label = four.comcode + '-' + four.name
                        four.children = four.chilDren || []
                      })
                    }
                  })
                }
              })
            }
          })
          console.log(arr);
          this.organizationList = arr
        } else {
          this.organizationList = [];
        }
      });
      // this.api.getAllOrganization().then(res => {
      //   if (res.code == 200 && res.data != null) {
      //     this.organizationList = res.data;
      //   }
      // });
      this.api.uerRankList().then(res => {
        if (res.code == 200 && res.data != null) {
          this.levelList = res.data
        }
      })
    },

    // 添加用户弹窗
    addUser() {
      this.addUserModal = true
    },
    modalVisibleChange(value) {
      // console.log(value)
      if (value == false) {
        this.addUserModal = false
        this.$refs.addUserForm.resetFields()
      }
    },
    changeOrganization(value, selectedData){
      console.log(value, selectedData);
    },
    // 保存新增
    addSubmit() {
      // this.stopModal = true;
      this.$refs.addUserForm.validate(valid => {
        if (valid) {
          this.addSubmitLoading = true
          this.addObj = {
            username: this.addUserForm.account,
            name: this.addUserForm.name,
            password: this.addUserForm.password,
            company: this.addUserForm.company,
            phone: this.addUserForm.phone,
            employeeNo: this.addUserForm.employeeNo,
            managecom: this.addUserForm.organization[this.addUserForm.organization.length-1],
            managecomName: this.addUserForm.organization.value,
            email: this.addUserForm.email,
            workAge: this.addUserForm.workYear,
            rankNo: this.addUserForm.level,
            sex: this.addUserForm.sex,
            isInnerLine: this.addUserForm.isInnerLine
          }

          // 判断工号
          if (this.addUserForm.employeeNo) {
            this.api
              .getOneLaagent({ no: this.addUserForm.employeeNo })
              .then(res => {
                if (res.code == 200) {
                  this.stopManagecom = res.data.managecom
                  // 判断机构
                  if (res.data.managecom != this.addUserForm.organization[this.addUserForm.organization.length-1]) {
                    this.stopModal = true
                  } else {
                    this.saveAdd()
                  }
                } else {
                  this.addSubmitLoading = false
                  this.$Message.info('未查询到对应工号，不可进行此操作')
                }
              })
          } else {
            this.saveAdd()
          }
        } else {
          this.addSubmitLoading = false
          this.$Message.info('信息填写有误')
        }
      })
    },

    saveAdd() {
      this.api.addUser(this.addObj).then(res => {
        if (res.code == 200 && res.data != null) {
          this.addSubmitLoading = false
          this.addUserForm = {
            account: '',
            name: '',
            password: '',
            company: '',
            rePassword: '',
            phone: '',
            employeeNo: '',
            organization: '',
            email: '',
            workYear: '',
            level: '',
            sex: '',
            isInnerLine:'',
          }
          this.$refs.addUserForm.resetFields()
          this.addUserModal = false
          this.userQuery(1)
          this.$Message.info(res.msg)
        } else {
          this.addSubmitLoading = false
          if (res.msg == "user.employeeNo'数据库中已存在") {
            this.$Message.info('工号已存在')
          } else if (res.msg == "user.username'数据库中已存在") {
            this.$Message.info('账号已存在')
          } else {
            this.$Message.info('信息修改失败')
          }
        }
      })
    },

    addCancel() {
      this.$refs.addUserForm.resetFields()
      this.addUserModal = false
      this.addSubmitLoading = false
    },
    stopModalChange(flag) {
      // console.log(flag)
      if (flag == false) {
        this.addSubmitLoading = false
      }
    },

    // 保存时，机构阻断
    stopSubmit() {
      this.saveAdd()
      this.stopModal = false
    },
    stopCancel() {
      this.addSubmitLoading = false
      this.stopModal = false
    },

    // 修改信息弹窗
    resetPswShow(row) {
      this.currentRow = row
      this.resetPswForm.oldCompany = row.company
      this.resetPswForm.workYear = row.workAge
      // this.resetPswForm.organization = row.managecom
      let arr = []
      this.organizationList.forEach(one=>{
        if (one.value == row.managecom) {
          arr.push(one.value)
        }else if(one.children){
          one.children.forEach(two=>{
            if (two.value == row.managecom) {
              arr.push(one.value,two.value)
            }else if (two.children) {
              two.children.forEach(three=>{
                if (three.value == row.managecom) {
                  arr.push(one.value,two.value,three.value)
                }else if(three.children){
                  three.children.forEach(four=>{
                    if (four.value == row.managecom) {
                      arr.push(one.value,two.value,three.value,four.value)
                    }
                  })
                }
              })
            }
          })
        }
      })
      console.log(arr,'arr');
      this.resetPswForm.organization = arr

      this.api.getUserByNo({ no: row.employeeNo }).then(res => {
        if (res.code == 200) {
          this.resetPswForm.workLevel = res.data.rankNo
          this.resetPswForm.sex = res.data.sex
        }
      })
      // console.log(this.resetPswForm)

      this.resetPswModal = true
    },

    // 修改信息弹窗变化
    modalVisibleChange2(value) {
      if (value == false) {
        this.$refs.resetPswForm.resetFields()
        this.resetPswModal = false
        this.repasswordSubmit = false
      }
    },
    // 修改信息取消
    resetPswCancel() {
      this.$refs.resetPswForm.resetFields()
      this.resetPswModal = false
      this.repasswordSubmit = false
    },
    stopModalChange2(flag) {
      // console.log(flag)
      if (flag == false) {
        this.repasswordSubmit = false
      }
    },

    // 修改信息确认
    resetPswSubmit() {
      this.$refs.resetPswForm.validate(valid => {
        if (valid) {
          this.repasswordSubmit = true
          this.updateObj = {
            username: this.currentRow.username,
            company: this.resetPswForm.oldCompany,
            managecom: this.resetPswForm.organization[this.resetPswForm.organization.length-1],
            rankNo: this.resetPswForm.workLevel,
            sex: this.resetPswForm.sex,
            workAge: this.resetPswForm.workYear
          }
          if (this.resetPswForm.password.length > 0) {
            this.updateObj.password = this.resetPswForm.password
          }
          if (
            this.resetPswForm.workLevel != 'S30' &&
            this.resetPswForm.workLevel != 'S31' &&
            this.resetPswForm.workLevel != 'S32'
          ) {
            this.api
              .getOneLaagent({ no: this.currentRow.employeeNo })
              .then(res => {
                if (res.code == 200) {
                  this.stopManagecom2 = res.data.managecom
                  // 判断机构
                  if (res.data.managecom != this.resetPswForm.organization[this.resetPswForm.organization.length-1]) {
                    this.stopModal2 = true
                  } else {
                    this.saveUpdate()
                  }
                } else {
                  this.repasswordSubmit = false
                  this.$Message.info('未查询到对应工号，不可进行此操作')
                }
              })
          } else {
            this.saveUpdate()
          }
        }
      })
    },
    saveUpdate() {
      this.api.resetPwd(this.updateObj).then(res => {
        if (res.code == 200) {
          this.repasswordSubmit = false
          this.resetPswModal = false
          this.$Message.info('信息修改成功')
          if (this.resetPswForm.password.length > 0) {
            Cookies.remove('user')
            Cookies.remove('password')
            Cookies.remove('hasGreet')
            Cookies.remove('access')
            Cookies.remove('principal')
            this.$store.commit('clearOpenedSubmenu')
            localStorage.clear()
            sessionStorage.clear()
            this.ModifyPasswordModal = false
            this.$Modal.info({
              title: '当前登录信息已失效，请重新登录！',
              okText: '确定',
              onOk: () => {
                this.$router.push({
                  name: 'login'
                })
              }
            })
          } else {
            this.$refs.resetPswForm.resetFields()
            this.userQuery(1)
          }
        } else {
          this.repasswordSubmit = false
          this.resetPswForm.password = ''
          this.resetPswForm.rePassword = ''
          if (res.msg == "user.employeeNo'数据库中已存在") {
            this.$Message.info('工号已存在')
          } else if (res.msg == "user.username'数据库中已存在") {
            this.$Message.info('账号已存在')
          } else {
            this.$Message.info('信息修改失败')
          }
        }
      })
    },
    // 保存时，机构阻断
    stopSubmit2() {
      this.saveUpdate()
      this.stopModal2 = false
    },
    stopCancel2() {
      this.repasswordSubmit = false
      this.stopModal2 = false
    }
  },
  mounted() {
    // 进入页面初始化
    this.initialize()
  }
}
</script>

<style lang="less" scoped>
@import './user';
</style>

<style scoped>
.ivu-modal-header {
  background-color: #2d8cf0;
}
.ivu-modal-close .ivu-icon-ios-close {
  color: #fff;
}

.stopClass > .ivu-modal {
  top: 0;
  left: 25px;
}
.addClass > .ivu-modal {
  top: 140px;
}
.updateClass > .ivu-modal {
  top: 140px;
}
.btngroup{
  width: 100%;
  display: flex;
  justify-content: center;
}
.btngroup .ivu-col-span-8{
  display: inline-block;
  width: 100px;
}
</style>
